Page({
  data: {
    services: [],
    filteredServices: [],
    totalServices: 0,
    activeServices: 0,
    selectedCategory: 'all',
    categories: [],
    showAddForm: false,
    editMode: false,
    editingId: '',
    formData: {
      title: '',
      description: '',
      category: '',
      price: '',
      unit: '',
      rating: '',
      image: '',
      badge: '',
      tags: []
    },
    tagsString: '',
    categoryIndex: -1,
    loading: false,
    loadingText: ''
  },

  onLoad() {
    console.log('服务管理页面加载')
    this.loadCategories()
    this.loadAllServices()
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadCategories()
    this.loadAllServices()
  },

  // 加载分类数据
  async loadCategories() {
    try {
      const result = await wx.cloud.callFunction({
        name: 'serviceManager',
        data: {
          action: 'getValidCategories'
        }
      })

      if (result.result.success) {
        const categories = result.result.data.map(category => ({
          key: category.code,
          name: category.name,
          icon: category.icon,
          color: category.color
        }))
        
        this.setData({
          categories: categories
        })
        
        console.log('加载分类数据成功，共', categories.length, '个分类')
      } else {
        console.error('加载分类数据失败:', result.result.error)
      }
    } catch (error) {
      console.error('加载分类数据异常:', error)
    }
  },

  // 加载所有服务
  async loadAllServices() {
    this.setData({
      loading: true,
      loadingText: '加载服务数据...'
    })

    try {
      const result = await wx.cloud.callFunction({
        name: 'serviceManager',
        data: {
          action: 'getAllServices'
        }
      })

      if (result.result.success) {
        const services = result.result.data || []
        const activeServices = services.filter(item => item.status === 'active').length
        
        this.setData({
          services: services,
          totalServices: services.length,
          activeServices: activeServices,
          loading: false
        })
        
        this.filterServices()
        console.log('加载服务数据成功，共', services.length, '条')
      } else {
        console.error('加载服务数据失败:', result.result.error)
        wx.showToast({
          title: '加载失败',
          icon: 'error'
        })
        this.setData({ loading: false })
      }
    } catch (error) {
      console.error('调用云函数失败:', error)
      wx.showToast({
        title: '网络异常',
        icon: 'error'
      })
      this.setData({ loading: false })
    }
  },

  // 筛选服务
  filterServices() {
    const { services, selectedCategory } = this.data
    let filteredServices = services

    if (selectedCategory !== 'all') {
      filteredServices = services.filter(item => item.category === selectedCategory)
    }

    this.setData({ filteredServices })
  },

  // 分类筛选
  onCategoryFilter(e) {
    const category = e.currentTarget.dataset.category
    this.setData({ selectedCategory: category })
    this.filterServices()
  },

  // 查看服务统计信息
  async viewServiceStats() {
    wx.showLoading({
      title: '加载统计信息...'
    })

    try {
      const result = await wx.cloud.callFunction({
        name: 'serviceManager',
        data: {
          action: 'getServiceStats'
        }
      })

      wx.hideLoading()

      if (result.result.success) {
        const stats = result.result.data
        let message = '📊 服务统计信息\n\n'
        message += `📋 总体概览:\n`
        message += `• 服务总数: ${stats.overview.totalServices}\n`
        message += `• 分类总数: ${stats.overview.totalCategories}\n\n`
        
        message += `📈 分类统计:\n`
        stats.categoryStats.forEach(stat => {
          message += `${stat.categoryIcon} ${stat.categoryName}: ${stat.serviceCount}个服务 (评分: ${stat.avgRating})\n`
        })
        
        message += `\n⭐ 评分最高的服务:\n`
        stats.topRatedServices.slice(0, 3).forEach((service, index) => {
          message += `${index + 1}. ${service.title} (${service.rating}⭐)\n`
        })

        wx.showModal({
          title: '📊 数据统计',
          content: message,
          showCancel: true,
          cancelText: '关闭',
          confirmText: '查看详情',
          success: (res) => {
            if (res.confirm) {
              this.showDetailedStats(stats)
            }
          }
        })
      } else {
        wx.showToast({
          title: '加载统计失败',
          icon: 'error'
        })
      }
    } catch (error) {
      wx.hideLoading()
      console.error('获取统计信息失败:', error)
      wx.showToast({
        title: '网络异常',
        icon: 'error'
      })
    }
  },

  // 显示详细统计信息
  showDetailedStats(stats) {
    wx.showActionSheet({
      itemList: ['查看分类详情', '查看热门服务', '查看最新服务', '导出统计报告'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            this.showCategoryDetails(stats.categoryStats)
            break
          case 1:
            this.showTopServices(stats.topRatedServices)
            break
          case 2:
            this.showLatestServices(stats.latestServices)
            break
          case 3:
            this.exportStatsReport(stats)
            break
        }
      }
    })
  },

  // 显示分类详情
  showCategoryDetails(categoryStats) {
    let message = '📊 各分类详细统计:\n\n'
    categoryStats.forEach(stat => {
      message += `${stat.categoryIcon} ${stat.categoryName}:\n`
      message += `  • 服务数量: ${stat.serviceCount}个\n`
      message += `  • 平均评分: ${stat.avgRating}⭐\n`
      message += `  • 分类代码: ${stat.categoryCode}\n\n`
    })

    wx.showModal({
      title: '分类统计详情',
      content: message,
      showCancel: false
    })
  },

  // 显示热门服务
  showTopServices(topServices) {
    let message = '⭐ 评分最高的服务:\n\n'
    topServices.forEach((service, index) => {
      message += `${index + 1}. ${service.title}\n`
      message += `   评分: ${service.rating}⭐ | 价格: ¥${service.price}/${service.unit}\n`
      message += `   分类: ${service.category}\n\n`
    })

    wx.showModal({
      title: '热门服务排行',
      content: message,
      showCancel: false
    })
  },

  // 显示最新服务
  showLatestServices(latestServices) {
    let message = '🆕 最新添加的服务:\n\n'
    latestServices.forEach((service, index) => {
      const date = this.formatDate(service.createTime)
      message += `${index + 1}. ${service.title}\n`
      message += `   添加时间: ${date}\n`
      message += `   分类: ${service.category} | 评分: ${service.rating}⭐\n\n`
    })

    wx.showModal({
      title: '最新服务',
      content: message,
      showCancel: false
    })
  },

  // 导出统计报告
  exportStatsReport(stats) {
          const date = this.formatDate(new Date())
    let report = `数智匠心工程 - 服务统计报告\n生成时间: ${date}\n\n`
    
    report += `===== 总体概览 =====\n`
    report += `服务总数: ${stats.overview.totalServices}\n`
    report += `分类总数: ${stats.overview.totalCategories}\n\n`
    
    report += `===== 分类统计 =====\n`
    stats.categoryStats.forEach(stat => {
      report += `${stat.categoryName} (${stat.categoryCode}):\n`
      report += `  服务数量: ${stat.serviceCount}\n`
      report += `  平均评分: ${stat.avgRating}\n\n`
    })
    
    report += `===== 热门服务 =====\n`
    stats.topRatedServices.forEach((service, index) => {
      report += `${index + 1}. ${service.title} (${service.rating}⭐)\n`
    })
    
    wx.setClipboardData({
      data: report,
      success: () => {
        wx.showToast({
          title: '报告已复制到剪贴板',
          icon: 'success'
        })
      }
    })
  },

  // 初始化服务数据
  async initServiceData() {
    wx.showModal({
      title: '确认操作',
      content: '确定要初始化服务数据吗？这将添加示例服务项。',
      success: async (res) => {
        if (res.confirm) {
          this.setData({
            loading: true,
            loadingText: '初始化服务数据...'
          })

          try {
            const result = await wx.cloud.callFunction({
              name: 'serviceManager',
              data: {
                action: 'initServiceData'
              }
            })

            this.setData({ loading: false })

            if (result.result.success) {
              wx.showModal({
                title: '初始化成功',
                content: `${result.result.message}\n插入了 ${result.result.count} 条服务数据`,
                showCancel: false,
                success: () => {
                  this.loadAllServices()
                }
              })
            } else {
              wx.showModal({
                title: '初始化失败',
                content: result.result.error,
                showCancel: false
              })
            }
          } catch (error) {
            this.setData({ loading: false })
            console.error('初始化失败:', error)
            wx.showToast({
              title: '初始化失败',
              icon: 'error'
            })
          }
        }
      }
    })
  },

  // 刷新服务列表
  refreshServiceList() {
    this.loadAllServices()
  },

  // 显示添加服务表单
  showAddServiceForm() {
    this.setData({
      showAddForm: true,
      editMode: false,
      editingId: '',
      formData: {
        title: '',
        description: '',
        category: '',
        price: '',
        unit: '',
        rating: '4.8',
        image: '',
        badge: '',
        tags: []
      },
      tagsString: '',
      categoryIndex: -1
    })
  },

  // 隐藏添加服务表单
  hideAddServiceForm() {
    this.setData({ showAddForm: false })
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 空函数，阻止点击modal内容时关闭弹窗
  },

  // 表单输入
  onFormInput(e) {
    const { field } = e.currentTarget.dataset
    const { value } = e.detail
    this.setData({
      [`formData.${field}`]: value
    })
  },

  // 标签输入
  onTagsInput(e) {
    const { value } = e.detail
    const tags = value.split(',').map(tag => tag.trim()).filter(tag => tag)
    this.setData({
      tagsString: value,
      'formData.tags': tags
    })
  },

  // 分类选择
  onCategoryChange(e) {
    const index = parseInt(e.detail.value)
    const category = this.data.categories[index]
    this.setData({
      categoryIndex: index,
      'formData.category': category.key
    })
  },

  // 编辑服务
  editService(e) {
    const service = e.currentTarget.dataset.service
    const categoryIndex = this.data.categories.findIndex(cat => cat.key === service.category)
    
    this.setData({
      showAddForm: true,
      editMode: true,
      editingId: service._id,
      formData: {
        title: service.title || '',
        description: service.description || '',
        category: service.category || '',
        price: service.price || '',
        unit: service.unit || '',
        rating: service.rating || '4.8',
        image: service.image || '',
        badge: service.badge || '',
        tags: service.tags || []
      },
      tagsString: (service.tags || []).join(','),
      categoryIndex: categoryIndex
    })
  },

  // 删除服务
  deleteService(e) {
    const serviceId = e.currentTarget.dataset.id
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个服务项吗？',
      success: async (res) => {
        if (res.confirm) {
          this.setData({
            loading: true,
            loadingText: '删除服务...'
          })

          try {
            const result = await wx.cloud.callFunction({
              name: 'serviceManager',
              data: {
                action: 'deleteService',
                serviceId: serviceId
              }
            })

            this.setData({ loading: false })

            if (result.result.success) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              })
              this.loadAllServices()
            } else {
              wx.showToast({
                title: '删除失败',
                icon: 'error'
              })
            }
          } catch (error) {
            this.setData({ loading: false })
            console.error('删除失败:', error)
            wx.showToast({
              title: '删除失败',
              icon: 'error'
            })
          }
        }
      }
    })
  },

  // 提交服务
  async submitService() {
    const { formData, editMode, editingId } = this.data
    
    // 表单验证
    if (!formData.title || !formData.description || !formData.category || !formData.price) {
      wx.showToast({
        title: '请填写必填项',
        icon: 'none'
      })
      return
    }

    this.setData({
      loading: true,
      loadingText: editMode ? '保存服务...' : '添加服务...'
    })

    try {
      const serviceData = {
        ...formData,
        price: parseFloat(formData.price) || 0,
        rating: parseFloat(formData.rating) || 4.8,
        sort: 1
      }

      const result = await wx.cloud.callFunction({
        name: 'serviceManager',
        data: {
          action: editMode ? 'updateService' : 'addService',
          serviceId: editMode ? editingId : undefined,
          serviceData: serviceData
        }
      })

      this.setData({ loading: false })

      if (result.result.success) {
        wx.showToast({
          title: editMode ? '保存成功' : '添加成功',
          icon: 'success'
        })
        this.hideAddServiceForm()
        this.loadAllServices()
      } else {
        wx.showToast({
          title: editMode ? '保存失败' : '添加失败',
          icon: 'error'
        })
      }
    } catch (error) {
      this.setData({ loading: false })
      console.error('提交失败:', error)
      wx.showToast({
        title: '提交失败',
        icon: 'error'
      })
    }
  },

  // 格式化日期
  formatDate(dateInput) {
    if (!dateInput) return ''
    
    try {
      let date
      
      // 处理不同的日期格式
      if (typeof dateInput === 'string') {
        date = new Date(dateInput)
      } else if (dateInput instanceof Date) {
        date = dateInput
      } else if (typeof dateInput === 'number') {
        date = new Date(dateInput)
      } else {
        date = new Date(String(dateInput))
      }
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        console.warn('❌ 无效的日期格式:', dateInput)
        return String(dateInput)
      }
      
      // 手动格式化，确保兼容性
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      
      return `${year}年${month}月${day}日`
      
    } catch (error) {
      console.error('❌ 格式化日期失败:', error, '原始数据:', dateInput)
      return String(dateInput)
    }
  }
}) 